Skip to content

Durga js fetch api debugging#545

Open
Saidurgasatturi wants to merge 2 commits intoaptyInc:mainfrom
Saidurgasatturi:durga-js-fetch_API_Debugging
Open

Durga js fetch api debugging#545
Saidurgasatturi wants to merge 2 commits intoaptyInc:mainfrom
Saidurgasatturi:durga-js-fetch_API_Debugging

Conversation

@Saidurgasatturi
Copy link
Copy Markdown

@Saidurgasatturi Saidurgasatturi commented Nov 10, 2025

Terms and Conditions

  • I Accept losing points if my PR does not follow the best practices mentioned below, which will impact my overall performance in training

HTML Best Practices

  • File Naming Convention:

  • Follow consistent and descriptive naming (e.g., dashboard.html, user-profile.html).

  • Use lowercase letters and hyphens instead of spaces.

  • Page Title:

  • Ensure the <title> tag is descriptive and aligns with the page content.

  • Include meaningful keywords for SEO if applicable.

  • Semantic Markup:

  • Use appropriate tags like <header>, <footer>, <section>, <article> for better readability and accessibility.

  • Accessibility Standards:

  • Ensure the use of alt attributes for images and proper labels for form elements.

  • Use ARIA roles where necessary.

  • Validation:

  • Ensure the code passes HTML validation tools without errors or warnings.

  • Structure and Indentation:

  • Maintain consistent indentation and proper nesting of tags.

  • Attributes:

  • Ensure all required attributes (e.g., src, href, type, etc.) are correctly used and not left empty.

CSS Best Practices

  • File Organization:

  • Use modular CSS files if applicable (e.g., base.css, layout.css, theme.css).

  • Avoid inline styles unless absolutely necessary.

  • Naming Conventions:

  • Use meaningful class names following BEM or other conventions (e.g., block__element--modifier).

  • Code Reusability:

  • Avoid duplicate code; use classes or mixins for shared styles.

  • Responsive Design:

  • Ensure proper usage of media queries for mobile, tablet, and desktop views.

  • Performance Optimization:

  • Minimize the use of unnecessary CSS selectors.

  • Avoid overly specific selectors and ensure selectors are not overly deep (e.g., avoid #id .class1 .class2 p).

  • Consistency:

  • Follow consistent spacing, indentation, and use of units (rem/em vs. px).

  • Maintain a single coding style (e.g., always use double or single quotes consistently).

Javascript Best Practices

  • File Organization:

  • Ensure scripts are modular and logically separated into files if needed.

  • Avoid mixing inline JavaScript with HTML.

  • Logic Optimization:

  • Check for redundancy and ensure the code is optimized for performance.

  • Avoid unnecessary API calls or DOM manipulations.

  • Solution Approach:

  • Confirm that the code solves the given problem efficiently.

  • Consider scalability for future enhancements.

  • Readability:

  • Use clear variable and function names.

  • Add comments for complex logic or algorithms.

  • Error Handling:

  • Ensure proper error handling for API calls or user input validation.

  • Code Quality:

  • Check for potential bugs (e.g., missing await, mishandling of null/undefined values).

  • Avoid unnecessary console.log statements in production code.

  • Security:

  • Avoid hardcoding sensitive data.

  • Sanitize user input to prevent XSS and other vulnerabilities.

  • Best Practices:

  • Use const and let instead of var.

  • Follow ES6+ standards where applicable.

@gemini-code-assist
Copy link
Copy Markdown

Summary of Changes

Hello @Saidurgasatturi, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces several new front-end assignments, primarily focusing on practical application of JavaScript's Fetch API and modern CSS techniques. It delivers a functional, albeit simple, e-commerce experience and separate examples for responsive design and animations, serving as foundational exercises for web development concepts.

Highlights

  • E-commerce Application Development: Implemented a simple e-commerce application featuring product listing, search functionality, and individual product detail pages, all powered by the Fetch API.
  • Fetch API Integration: Utilized the JavaScript Fetch API to asynchronously retrieve product data from an external API (dummyjson.com) for both the main product display and individual product details.
  • Responsive Design and CSS Animations: Introduced new CSS assignments demonstrating responsive layouts using flexbox and media queries, as well as a basic CSS animation example.
  • Modular Front-end Structure: Organized the e-commerce application into separate HTML, CSS, and JavaScript files, following best practices for maintainability and readability.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces several new files for CSS and JavaScript assignments. My review focuses on improving security, code organization, and adherence to web development best practices. The most critical issues are related to Cross-Site Scripting (XSS) vulnerabilities due to the use of innerHTML with data fetched from an external API. I've also provided feedback on separating CSS and JavaScript from HTML files, improving user experience by avoiding alert(), and correctly encoding URL parameters. Addressing these points will make the code more secure, maintainable, and robust.

Comment on lines +26 to +34
container.innerHTML = `
<img src="${product.thumbnail}" alt="${product.title}">
<h2>${product.title}</h2>
<p>${product.description}</p>
<p><strong>Price:</strong> $${product.price}</p>
<p><strong>Brand:</strong> ${product.brand}</p>
<p><strong>Category:</strong> ${product.category}</p>
<button onclick="window.history.back()">⬅️ Go Back</button>
`;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Using innerHTML to inject content from an API response can expose your application to Cross-Site Scripting (XSS) attacks if the fetched data contains malicious scripts. It's much safer to create DOM elements programmatically and set their content using properties like textContent, which prevents string content from being parsed as HTML.

Comment on lines +33 to +44
productContainer.innerHTML = products
.map(
(p) => `
<div class="product-card">
<img src="${p.thumbnail}" alt="${p.title}">
<h3>${p.title}</h3>
<p>$${p.price}</p>
<button onclick="viewProduct(${p.id})">View Details</button>
</div>
`
)
.join("");
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Using innerHTML to render a list of items from an API is a significant security risk, making the application vulnerable to Cross-Site Scripting (XSS). Additionally, using inline onclick handlers is not a modern best practice. The recommended approach is to create DOM elements for each product card programmatically, use textContent to safely insert data, and attach event listeners with addEventListener.

@media (max-width: 768px) {
main {
flex-direction: column;
flex:1;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The flex: 1 property here has no effect. main is a flex container, but it is not a flex item of another flex container (its parent, body, does not have display: flex by default). You can safely remove this line.

Comment on lines +7 to +55
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background: #f0f0f0;
}
.box {
width: 150px;
height: 150px;
background: #3498db;
border-radius: 10px;
display: flex;
justify-content: center;
align-items: center;
color: white;
font-weight: bold;
animation: bounce 2s infinite;
}
@keyframes bounce {
0%, 100% {
transform: translateY(0);
}
50% {
transform: translateY(-50px);
}
}
@media (max-width: 768px) {
.box {
width: 120px;
height: 120px;
font-size: 14px;
background: #e67e22;
}
}

@media (max-width: 480px) {
.box {
width: 90px;
height: 90px;
font-size: 12px;
background: #2ecc71;
}
}
</style>
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

It's a best practice to keep your CSS in a separate file rather than embedding it within a <style> tag in your HTML. This improves code organization, reusability, and browser caching. Consider creating a separate .css file and linking it in the <head> using a <link> tag.

Comment on lines +15 to +41
<script>
async function loadProductDetails() {
const params = new URLSearchParams(window.location.search);
const id = params.get("id");

try {
const res = await fetch(`https://dummyjson.com/products/${id}`);
if (!res.ok) throw new Error("Failed to fetch product details");
const product = await res.json();

const container = document.getElementById("productDetails");
container.innerHTML = `
<img src="${product.thumbnail}" alt="${product.title}">
<h2>${product.title}</h2>
<p>${product.description}</p>
<p><strong>Price:</strong> $${product.price}</p>
<p><strong>Brand:</strong> ${product.brand}</p>
<p><strong>Category:</strong> ${product.category}</p>
<button onclick="window.history.back()">⬅️ Go Back</button>
`;
} catch (error) {
document.getElementById("productDetails").innerHTML = `<p>Error: ${error.message}</p>`;
}
}

loadProductDetails();
</script>
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

For better code organization and maintainability, it's a best practice to move JavaScript code out of HTML files. Consider creating a separate product-details.js file and including it with <script src="product-details.js" defer></script> just before the closing </body> tag.

<button onclick="window.history.back()">⬅️ Go Back</button>
`;
} catch (error) {
document.getElementById("productDetails").innerHTML = `<p>Error: ${error.message}</p>`;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using innerHTML to display an error message can be a security risk if the error.message can be manipulated. It's safer to use textContent to prevent any potential HTML injection.

Suggested change
document.getElementById("productDetails").innerHTML = `<p>Error: ${error.message}</p>`;
document.getElementById("productDetails").textContent = `Error: ${error.message}`;

const data = await res.json();
displayProducts(data.products);
} catch (error) {
productContainer.innerHTML = `<p>Error: ${error.message}</p>`;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using innerHTML to display an error message can be a security risk if the error.message can be manipulated. It's safer to use textContent to prevent any potential HTML injection.

Suggested change
productContainer.innerHTML = `<p>Error: ${error.message}</p>`;
productContainer.textContent = `Error: ${error.message}`;


async function searchProducts(query) {
try {
const res = await fetch(`https://dummyjson.com/products/search?q=${query}`);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The search query should be properly encoded before being included in a URL to handle special characters (e.g., &, ?, ) correctly. Using encodeURIComponent() ensures the query is treated as a single, safe string parameter.

Suggested change
const res = await fetch(`https://dummyjson.com/products/search?q=${query}`);
const res = await fetch(`https://dummyjson.com/products/search?q=${encodeURIComponent(query)}`);

const data = await res.json();
displayProducts(data.products);
} catch (error) {
productContainer.innerHTML = `<p>Error: ${error.message}</p>`;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using innerHTML to display an error message can be a security risk if the error.message can be manipulated. It's safer to use textContent to prevent any potential HTML injection.

Suggested change
productContainer.innerHTML = `<p>Error: ${error.message}</p>`;
productContainer.textContent = `Error: ${error.message}`;

searchBtn.addEventListener("click", () => {
const query = searchInput.value.trim();
if (query) searchProducts(query);
else alert("Please enter something to search!");
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using alert() provides a poor user experience because it's a blocking modal dialog. A better approach is to display a non-blocking message within the UI, for instance, by adding a text element near the search bar or changing the input's placeholder text temporarily.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant